package cn.com.nes.site.service.logs.impl;

import cn.com.nes.common.util.DistinctByPropertyUtils;
import cn.com.nes.mybatis.agent.logs.entity.ImportLogDetails;
import cn.com.nes.mybatis.agent.logs.mapper.ImportLogDetailsMapper;
import cn.com.nes.mybatis.agent.logs.mapper.ImportLogsMapper;
import cn.com.nes.site.entity.PageData;
import cn.com.nes.site.entity.iot.CustomerSurveyExcel;
import cn.com.nes.site.entity.vo.NullVO;
import cn.com.nes.site.service.logs.ImportLogDetailsService;
import cn.com.nes.site.service.logs.bo.ImportDetailLogPageBO;
import cn.com.nes.site.service.logs.dto.ImportDetailLogDTO;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
@Slf4j
public class ImportLogDetailsServiceImpl extends ServiceImpl<ImportLogDetailsMapper, ImportLogDetails> implements ImportLogDetailsService {

    @Resource
    ImportLogDetailsMapper ImportLogDetailsMapper;

    @Resource
    ImportLogsMapper importLogsMapper;

    @Override
    @Transactional
    public void insertCustomerInfoDetailsData(ImportLogDetails importLogDetails) {
        // 插入错误详情表
        Integer rows = ImportLogDetailsMapper.insert(importLogDetails);
        if (rows <= 0) {
            log.error("保存错误详情数据失败");
            return;
        }
        // 插入主表，错误数量加1
        importLogsMapper.updateCustomerInfoData(importLogDetails.getProjectId() + "", importLogDetails.getDrpc());
    }

    @Override
    public PageData queryCustomerInfoData(ImportLogDetails importLogDetails) {
        Page<ImportLogDetails> page = new Page<>(importLogDetails.getPageid(), importLogDetails.getPagesize());
        List<ImportLogDetails> list = ImportLogDetailsMapper.queryCustomerInfoData(page, importLogDetails);
        return PageData.ok(page, list);
    }

    @Override
    public Page<ImportDetailLogDTO> importDetaiLogPage(ImportDetailLogPageBO bo) throws Exception {
        Page<ImportDetailLogDTO> page = new Page<>(bo.getPageid(), bo.getPagesize());
        List<ImportDetailLogDTO> list = this.baseMapper.importDetaiLogPage(page, bo);
        page.setRecords(list);
        return page;
    }

    // 切出一个新的事务，避免主业务异常后回滚异常日志
    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void AspectInsertDetailsData(CustomerSurveyExcel item, NullVO parentVo, String message, String type) {
        DistinctByPropertyUtils.insertDetailsData(this, item, parentVo, message, type);
    }

}
